#!/bin/sh

#
# Test the GPT creation ability of fwup
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(EFI_TYPE, "c12a7328-f81f-11d2-ba4b-00a0c93ec93b")
define(LINUX_TYPE, "44479540-f297-41b2-9af7-d131d5f0458a")

define(DISK_UUID, "b443fbeb-2c93-481b-88b3-0ecb0aeba911")
define(EFI_PART_UUID, "5278721d-0089-4768-85df-b8f1b97e6684")
define(ROOTFS_PART_UUID, "fcc205c8-2f1c-4dcd-bef4-7b209aa15cca")

define(EFI_PART_OFFSET, 64)
define(EFI_PART_COUNT, 32768)
define-eval(ROOTFS_PART_OFFSET, "\${EFI_PART_OFFSET} + \${EFI_PART_COUNT}")
define(ROOTFS_PART_COUNT, 65536)

gpt gpt-a {
    guid = \${DISK_UUID}

    partition 0 {
        block-offset = \${EFI_PART_OFFSET}
        block-count = \${EFI_PART_COUNT}
        type = \${EFI_TYPE}
        guid = \${EFI_PART_UUID}
        name = "efi-part.vfat"
        flags = 0x1
    }
    partition 1 {
        block-offset = \${ROOTFS_PART_OFFSET}
        block-count = \${ROOTFS_PART_COUNT}
        type = \${LINUX_TYPE}
        guid = \${ROOTFS_PART_UUID}
        name = "rootfs.ext2"
        flags = 0xc000000000004
    }
}
task complete {
	on-init {
                gpt_write(gpt-a)
        }
}
EOF

# Create the expected output from sfdisk by running ./168_gpt_flags-generate.sh on
# Linux.
base64_decodez >$WORK/expected-primary-gpt.img <<EOF
H4sIAPmku10AA+3SzysEYRzH8e9sXKStPSObkzY/4qQUM7F2kdLGbS9z2I2DaHfTltIcKOsqqT1x
5MgecFC42N0cKGfluiWkKGo87DN/wO6B1Ps1zTzf53nmeT7N9IjgP/PJo+u6hqpsx6h59exBeGw8
OG3FZkQMiasRa2Eg9D3j7eXt2qH7pu5XPkYKW10t0Y0jf7mpsh/w6XlH3xOXhYf6vgi/qTMdOm9/
vw2cTspucag42JbKxnIyF1m/P34+WU2umfq9YafaeuciIUmZl25ZEltSkpEeWVYjtqpqY25HRnde
Dq38203f3VN486rx4rO193rq7HUlmN+Ll0zHy68mN/w8m1XmoroyKjOtshOSVXV//b8BAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAP7cF+PCbYMAQgAA
EOF
base64_decodez >$WORK/expected-secondary-gpt.img <<EOF
H4sIAPmku10AA+3bvUoDQRSG4SNoIyKkVjFYiWiCtoLuomv8QZCQMs0WCVopSZCAIFsoqK1IIJVi
ZSVoimghGBuTYKFgLdqmUREUTJFZd/YC1kIs3meYOTOn+ZgLOIPZoev+r4fQ5YIcVieq432ZfHxX
lmPbT+W3i830liGeScerbfqdkrSsyIisiS0ZyUlE1lXHVrdgjIPYdOH9zCx+3o8+vlp7tx2VZm/0
bvHqYyNcPErWDMfP95Lbf84ulbmqVk5lZlV2SvLqPhYwGwAAAAAAAAAAAAAAAAAAAAAAAAAAAACA
/8KamQsvmfGEO9mfVO/n8vGp27f1vL0/7z+gq6H7je+p0v5wz+zOeXe9s3ESMnXf0Xv+pvTyV3/A
77UA9VungwBCAAA=
EOF
cp $WORK/expected-primary-gpt.img $WORK/expected.img
dd if=$WORK/expected-secondary-gpt.img of=$WORK/expected.img bs=512 seek=98369 conv=notrunc

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

# The firmware file is equivalent to the following dd call
cmp_bytes 50381824 $WORK/expected.img $IMGFILE

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
